package net.rokyinfo.appcontroller.util;

import net.rokyinfo.basecommon.config.SpringContainer;
import net.rokyinfo.basecommon.constant.RedisPrefixConstants;
import net.rokyinfo.basedao.dao.UserDao;
import net.rokyinfo.basedao.entity.User;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2017-03-16.
 */
public class UserCacheUtil {

    public static void putUserInfo2Redis(){
        UserDao userDao =  (UserDao)SpringContainer.getSpringContainer().getBean("userDao");
        List<User> userList = userDao.getAll();
        if (userList != null && userList.size() > 0){

            ShardedJedisPool shardedJedisPool = SpringContainer.getSpringContainer().getShardedJedisPool();
            ShardedJedis jedis = shardedJedisPool.getResource();
            try {
                //添加数据
                userList.forEach(user -> {
                    jedis.set(RedisPrefixConstants.EBIKE_USER_INFO + user.getUsername(),user2RedisValue(user));
                });
            } finally {
                shardedJedisPool.returnResource(jedis);
            }
        }

    }

    public static User getUserFromRedisValue(String userInfo){

        String[] userInfoArray = userInfo.split(":");
        if (userInfoArray.length >= 3){
            User user = new User();
            user.setUsername(userInfoArray[0]);
            user.setPassword2(userInfoArray[1]);
            user.setFirmId(Integer.parseInt(userInfoArray[2]));
            return user;

        }

        return null;
    }


    public static String user2RedisValue(User user){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(user.getUsername());
        stringBuilder.append(":");
        stringBuilder.append(user.getPassword2());
        stringBuilder.append(":");
        stringBuilder.append(user.getFirmId());
        return stringBuilder.toString();
    }

}
